from peewee import *
from ..database import database, TABLE_PREFIX, ModelMixin
from .product import Product
from .member import Member
import datetime


class Offer(database.Model,ModelMixin):
    id = PrimaryKeyField(db_column='id')
    status = CharField(db_column='status', help_text='状态', default='normal')
    count = IntegerField(db_column='count', help_text='库存数量', default=0)
    sales_count = IntegerField(db_column='sales_count', help_text='已售数量', default=0)
    slug = CharField(db_column='slug', help_text='产品库存类别', max_length=20, null=True)
    product = ForeignKeyField(Product, help_text='产品')
    member = ForeignKeyField(Member, help_text='所属会员')
    price = DecimalField(max_digits=15, decimal_places=4, auto_round=True, help_text='售价')
    # suggest_flag = CharField(db_column='suggest_flag', help_text='推荐标志', default='N')
    mask = CharField(max_length=80, help_text='标志掩码', default='')
    created_at = DateTimeField(db_column='created_at', help_text='创建日期', default=datetime.datetime.now)
    updated_at = DateTimeField(db_column='updated_at', help_text='更新日期', default=datetime.datetime.now)

    # class Meta:
    #     db_table = '{}_{}'.format(TABLE_PREFIX, 'stocks')

    @classmethod
    def stat_price(cls, product, currency=None):
        stat = cls.select(fn.Min(cls.price).alias('minimum'), fn.Avg(cls.price).alias('average'),
                          fn.Max(cls.price).alias('maximum')).where(cls.product == product).get()

        if stat and currency:
            for attr in ('minimum', 'average', 'maximum'):
                if hasattr(stat, attr):
                    value = getattr(stat, attr)
                    if value:
                        setattr(stat, attr, cls.convert_currency(getattr(stat, attr), currency))
                    else:
                        setattr(stat, attr, 0)
        return stat

    @classmethod
    def get_list(cls, product):
        return cls.select().where(cls.product == product).where(cls.count > cls.sales_count)

    def is_recommend(self):
        return self.mask.find('R') > 0

    @classmethod
    def convert_currency(cls, amount, currency):
        from decimal import Decimal
        rate = currency.rate if isinstance(currency.rate, Decimal) else  Decimal.from_float(currency.rate)

        amount = amount if isinstance(amount, Decimal) else Decimal.from_float(amount)

        return round(amount * rate, 2)

    @classmethod
    def get_min_and_max_price(cls, product):
        return cls.select(fn.Min(cls.price).alias('min_price'), fn.Max(cls.price).alias('max_price')).where(
            cls.product == product).first()
